<?php
require_once __DIR__ . '/Security.class.php';

// 兼容性函数：在命令行环境中替代getallheaders()
if (!function_exists('getallheaders')) {
    function getallheaders() {
        $headers = [];
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) === 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}

class Auth {
    private $conn;

    public function __construct(PDO $conn) {
        $this->conn = $conn;
    }

    /**
     * 检查管理员权限
     * @throws Exception
     */
    public function checkAdmin(): void {
        $token = $this->getBearerToken();
        $user = $this->validateToken($token);
        
        // 检查用户权限
        if (!in_array($user['permission'], ['admin', 'superadmin', 'assistant'])) {
            throw new Exception("权限不足，需要管理员权限", 403);
        }
    }

    /**
     * 检查超级管理员权限
     * @throws Exception
     */
    public function checkSuperAdmin(): void {
        $token = $this->getBearerToken();
        $user = $this->validateToken($token);
        
        // 检查用户权限
        if ($user['permission'] !== 'superadmin') {
            throw new Exception("权限不足，需要超级管理员权限", 403);
        }
    }

    /**
     * 从请求头获取Token
     * @throws Exception
     */
    public function getBearerToken(): string {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';

        if (empty($authHeader)) {
            throw new Exception("缺少Token", 401);
        }

        if (preg_match('/Bearer\s+(\S+)/i', $authHeader, $matches)) {
            return trim($matches[1]);
        }

        throw new Exception("Token格式错误", 401);
    }

    /**
     * 验证Token有效性并返回用户信息
     * @param string $token 用户Token
     * @return array 用户信息
     * @throws Exception
     */
    public function validateToken(string $token): array {
        // 统一验证用户Token（包括主账号和子账号）
        $stmt = $this->conn->prepare(
            "
            SELECT id, username, permission, position, token_expire, status, is_sub, parent_user_id, company_id
            FROM users
            WHERE token = :token
            LIMIT 1
        "
        );
        
        $stmt->execute([':token' => $token]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        // 如果Token有效
        if ($user) {
            if ($user['token_expire'] < time()) {
                throw new Exception("Token已过期", 403);
            }

            // 检查用户状态
            if ($user['status'] != 1) {
                throw new Exception("账号已被禁用", 403);
            }

            return $user;
        }

        // Token无效
        throw new Exception("无效的Token", 403);
    }

    /**
     * 使Token失效
     * @param int $userId 用户ID
     */
    public function invalidateToken(int $userId): void {
        $stmt = $this->conn->prepare("
            UPDATE users
            SET
                token = NULL,
                token_expire = NULL
            WHERE id = :id
        ");
        $stmt->execute([':id' => $userId]);
    }

    /**
     * 获取用户ID (兼容旧代码)
     */
    public function getUserId(): int {
        try {
            $token = $this->getBearerToken();
            $user = $this->validateToken($token);
            return $user['id'];
        } catch (Exception $e) {
            return 0;
        }
    }

    /**
     * 获取当前用户权限
     */
    public function getPermission(): string {
        try {
            $token = $this->getBearerToken();
            $user = $this->validateToken($token);
            return $user['permission'] ?? 'member';
        } catch (Exception $e) {
            return 'member';
        }
    }
    
    /**
     * 检查是否为子账号
     */
    public function isSubAccount(): bool {
        try {
            $token = $this->getBearerToken();
            $user = $this->validateToken($token);
            return $user['is_sub'] == 1;
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * 获取子账号信息（现在直接从users表获取）
     */
    public function getSubAccountInfo(): array {
        try {
            $token = $this->getBearerToken();
            $user = $this->validateToken($token);
            // 如果是子账号，返回用户信息
            if ($user['is_sub'] == 1) {
                return $user;
            }
            return [];
        } catch (Exception $e) {
            return [];
        }
    }
    
    /**
     * 获取用户公司ID
     */
    public function getCompanyId(): int {
        try {
            $token = $this->getBearerToken();
            $user = $this->validateToken($token);
            return $user['company_id'] ?? 0;
        } catch (Exception $e) {
            return 0;
        }
    }
}